<template>
    <div>
        <span class="centered-text">
            数智工班
        </span>
        <van-cell-group inset>
            <van-field v-model="loginForm.username" name="username" label="用户名" left-icon="contact"
                :rules="rules.username" is-link placeholder="请输入用户名" />
            <van-field v-model="loginForm.password" type="password" name="password" label="密码" left-icon="lock"
                :rules="rules.password" is-link placeholder="请输入密码" />
        </van-cell-group>
        <div class="login-button">
            <van-button block type="primary" @click="onSubmit">
                {{ loginButtonText }}
            </van-button>
        </div>
    </div>
</template>
<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import useStore from "@/store/index";
import { useCookies } from "vue3-cookies";
import { showLoadingToast, closeToast } from 'vant';
import userAPI from "@/api/user";
import dictAPI from "@/api/dict";
import { md5 } from "@/utils/MD5";
import { errorNotify, clearAllCaches } from "@/utils/Misc";
const store = useStore();
const router = useRouter();
const { cookies } = useCookies();
const loginButtonText = ref("登录");
const loginForm = ref({
    username: "",
    password: "",
});
const rules = {
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};
const onSubmit = async () => {
    try {
        loginButtonText.value = "登录中...";
        const loginParams = {
            username: loginForm.value.username,
            password: md5(loginForm.value.password)
        };
        const userRes = await userAPI.login(loginParams);
        const currentNo = userRes.data.sysUser.no;
        const storedNo = store.user && store.user.no;
        if (storedNo && storedNo !== currentNo) {
            await clearAllCaches();
        }
        cookies.set("token", userRes.data.sysUser.token);
        store.setUser(userRes.data.sysUser);
        loginButtonText.value = "数据加载中...";
        const dictRes = await dictAPI.list();
        store.setDict(dictRes.data.dictTree);
        closeToast();
        router.push("/home");
    } catch (error) {
        if (error?.response?.data?.msg == "账号或密码错误") {
            loginButtonText.value = "登录";
            return
        }
        errorNotify("Login.vue", "onSubmit", error);
    }
};
</script>
<style scoped>
.centered-text {
    margin: 180px 0 30px;
    display: block;
    text-align: center;
    font-weight: bolder;
    font-size: 25px;
    color: #022a77;
}

.login-button {
    margin: 1rem 1rem 0 1rem;
}
</style>